package com.boyuan.huijiaoyu;

import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.boyuan.huijiaoyu.R;
import com.magicsoft.app.adapter.SelectCommunityAdapter;
import com.magicsoft.app.entity.AuthorizationListResp;
import com.magicsoft.app.entity.CommunityResp;
import com.magicsoft.app.helper.DateUtils;
import com.magicsoft.app.helper.SharePreferenceHelper;
import com.magicsoft.app.helper.ToastHelper;
import com.magicsoft.app.wcf.DoorControlService;
import com.magicsoft.app.wcf.listener.GetOneRecordListener;
import com.magicsoft.weitown.ui.SelectCommunityDialog;
import com.ttcaca.cas.android.client.model.User;

/**
 * 授权批复
 * 
 * @author liqingjun
 * 
 */
public class DoorControlAuthorizationApproveActivity extends BaseActivity
		implements OnClickListener {

	private final static String TAG = "DoorControlAuthorizationApproveActivity";
	// 是否为批复页面 true为批复 false为再次授权
	private boolean isApprove = true;
	// 返回
	private Button btn_back;
	// 标题
	private TextView tv_title;
	// 申请人姓名
	private TextView tv_name;
	// // 申请时间
	// private TextView tv_time;
	// 备注
	private TextView tv_memo;
	// 小区
	private TextView tv_community;
	private ImageView iv_left_arrow;
	/* 授权类型 */// 授权类型，1=永久，2=7天，3=1天,4=2小时，5 = 1年
	private String usertype = "4";
	// 永久
	private Button btn_forever;
	// 1年
	private Button btn_1_year;
	// 7天
	private Button btn_7_day;
	// 1天
	private Button btn_1_day;
	// 2小时
	private Button btn_2_hour;
	// 批复按钮布局 批复时显示
	private LinearLayout li_approve;
	// 通过
	private Button btn_pass;
	// 拒绝
	private Button btn_reject;
	// 确定 在此授权时使用
	private Button btn_ensure;
	// 当前授权信息
	private AuthorizationListResp authorizationListResp;
	// 门禁网络服务
	private DoorControlService doorControlService;
	// 账户信息
	private User account;
	// 小区列表
	private List<CommunityResp> communityList = new ArrayList<CommunityResp>();
	// 当前小区
	private CommunityResp communityResp;
	// 保存小区选中状态 哪一个小区被选中
	private int whichCommunitySel = -1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.door_control_authorization_approve_activity);

		getIntentData();

		prepareView();

		prepareData();
	}

	/**
	 * 获取Intent传过来的数据
	 */
	private void getIntentData() {

		Intent intent = getIntent();
		isApprove = intent.getBooleanExtra("isApprove", false);
		authorizationListResp = (AuthorizationListResp) intent
				.getSerializableExtra("authorizationListResp");

	}

	private void prepareView() {
		// 标题
		tv_title = (TextView) findViewById(R.id.tv_title);
		// 返回
		btn_back = (Button) findViewById(R.id.btn_back);
		btn_back.setOnClickListener(this);
		// 申请人姓名
		tv_name = (TextView) findViewById(R.id.tv_name);
		// 小区
		tv_community = (TextView) findViewById(R.id.tv_community);
		tv_community.setOnClickListener(this);
		iv_left_arrow = (ImageView) findViewById(R.id.iv_left_arrow);
		iv_left_arrow.setOnClickListener(this);
		// 永久
		btn_forever = (Button) findViewById(R.id.btn_forever);
		btn_forever.setOnClickListener(this);
		// 1年
		btn_1_year = (Button) findViewById(R.id.btn_1_year);
		btn_1_year.setOnClickListener(this);
		// 7天
		btn_7_day = (Button) findViewById(R.id.btn_7_day);
		btn_7_day.setOnClickListener(this);
		// 1天
		btn_1_day = (Button) findViewById(R.id.btn_1_day);
		btn_1_day.setOnClickListener(this);
		// 2小时
		btn_2_hour = (Button) findViewById(R.id.btn_2_hour);
		btn_2_hour.setOnClickListener(this);
		btn_2_hour.setSelected(true);
		// // 申请时间
		// tv_time = (TextView) findViewById(R.id.tv_time);
		// li_approve
		li_approve = (LinearLayout) findViewById(R.id.li_approve);
		// 备注
		tv_memo = (TextView) findViewById(R.id.tv_memo);
		// 通过
		btn_pass = (Button) findViewById(R.id.btn_pass);
		btn_pass.setOnClickListener(this);
		// 拒绝
		btn_reject = (Button) findViewById(R.id.btn_reject);
		btn_reject.setOnClickListener(this);
		// 确定 在此授权时使用
		btn_ensure = (Button) findViewById(R.id.btn_ensure);
		btn_ensure.setOnClickListener(this);
	}

	private void prepareData() {

		account = SharePreferenceHelper.GetAccount(getApplicationContext());

		if (account != null) {
			List<CommunityResp> list = SharePreferenceHelper.getCommunityList(
					getApplicationContext(), account.getUid());

			if (list != null && list.size() > 0) {
				communityList.addAll(list);
			}
		}

		if (isApprove) {
			tv_title.setText("批复");
			li_approve.setVisibility(View.VISIBLE);
			btn_ensure.setVisibility(View.GONE);
		} else {
			tv_title.setText("再次授权");
			li_approve.setVisibility(View.GONE);
			btn_ensure.setVisibility(View.VISIBLE);
		}

		if (authorizationListResp != null) {
			// 被授权人姓名
			tv_name.setText(authorizationListResp.getToname());

			if (isApprove) {
				// 批复 默认第一个小区
				if (communityList.size() > 0) {
					communityResp = communityList.get(0);
					whichCommunitySel = 0;
				}
			} else {
				// 再次授权 对应之前授权小区
				for (int i = 0; i < communityList.size(); i++) {
					CommunityResp cResp = communityList.get(i);
					if (cResp.getBid().equals(authorizationListResp.getBid())) {
						communityResp = cResp;
						whichCommunitySel = i;
						break;
					}
				}
			}

			// 小区
			tv_community.setText(communityResp.getName());
			if (communityList.size() > 1) {
				iv_left_arrow.setVisibility(View.VISIBLE);
			} else {
				iv_left_arrow.setVisibility(View.INVISIBLE);
			}
			Log.i(TAG, "communityResp.getName = " + communityResp.getName());

			String auType = authorizationListResp.getUsertype();
			// 绿色
			// 默认
			if ("1".equals(auType)) {
				setTypeView(1);
			} else if ("2".equals(auType)) {
				setTypeView(2);
			} else if ("3".equals(auType)) {
				setTypeView(3);
			} else if ("4".equals(auType)) {
				setTypeView(4);
			} else if ("5".equals(auType)) {
				setTypeView(5);
			}
			// // 授权时间
			// tv_time.setText(DateUtils.phpToTimeString(authorizationListResp
			// .getCreationtime()));
			// 备注
			tv_memo.setText(authorizationListResp.getMemo());
		}
	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		// 返回
		case R.id.btn_back:
			onBackPressed();
			break;
		case R.id.tv_community:
		case R.id.iv_left_arrow:
			if (communityList.size() > 1) {
				// 选择小区
				selectCommunity();
			} else {
				// TODO 只有一个小区
			}
			break;
		case R.id.btn_forever:
			// 永久
			setTypeView(1);
			break;
		case R.id.btn_1_year:
			// 一年
			setTypeView(5);
			break;
		case R.id.btn_7_day:
			// 7天
			setTypeView(2);
			break;
		case R.id.btn_1_day:
			// 1天
			setTypeView(3);
			break;
		case R.id.btn_2_hour:
			// 两小时
			setTypeView(4);
			break;
		case R.id.btn_pass:
			// 通过
			approve("1");
			break;
		case R.id.btn_reject:
			// 拒绝
			approve("2");
			break;
		case R.id.btn_ensure:
			// 再次授权确定
			authorize();
			break;

		default:
			break;
		}
	}

	/**
	 * 选择类型设置布局
	 * 
	 * @param which
	 *            1永久 2限时 3临时
	 */
	public void setTypeView(int which) {

		Log.i(TAG, "which = " + which);
		switch (which) {

		case 1:
			// 永久
			usertype = "1";
			btn_forever.setSelected(true);
			btn_1_year.setSelected(false);
			btn_7_day.setSelected(false);
			btn_1_day.setSelected(false);
			btn_2_hour.setSelected(false);
			break;
		case 2:
			// 七天
			usertype = "2";
			btn_forever.setSelected(false);
			btn_1_year.setSelected(false);
			btn_7_day.setSelected(true);
			btn_1_day.setSelected(false);
			btn_2_hour.setSelected(false);
			break;
		case 3:
			// 一天
			usertype = "3";
			btn_forever.setSelected(false);
			btn_1_year.setSelected(false);
			btn_7_day.setSelected(false);
			btn_1_day.setSelected(true);
			btn_2_hour.setSelected(false);
			break;
		case 4:
			// 两小时
			usertype = "4";
			btn_forever.setSelected(false);
			btn_1_year.setSelected(false);
			btn_7_day.setSelected(false);
			btn_1_day.setSelected(false);
			btn_2_hour.setSelected(true);
			break;
		case 5:
			// 一年
			usertype = "5";
			btn_forever.setSelected(false);
			btn_1_year.setSelected(true);
			btn_7_day.setSelected(false);
			btn_1_day.setSelected(false);
			btn_2_hour.setSelected(false);
			break;
		}
	}

	/**
	 * 选择小区弹窗
	 */
	private void selectCommunity() {

		final SelectCommunityDialog dialog = new SelectCommunityDialog(
				DoorControlAuthorizationApproveActivity.this,
				R.style.selectorDialog);
		dialog.setCanceledOnTouchOutside(true);
		dialog.show();

		// 添加选项名称
		TextView tv_title = (TextView) dialog.findViewById(R.id.tv_title);
		tv_title.setText("选择小区");

		ListView listView = (ListView) dialog.findViewById(R.id.listview);

		final SelectCommunityAdapter adapter = new SelectCommunityAdapter(
				DoorControlAuthorizationApproveActivity.this, communityList,
				whichCommunitySel);

		listView.setAdapter(adapter);
		
		if (communityList != null && communityList.size() > 3) {
			setListViewHeightBasedOnChildren(listView);
		}

		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				CommunityResp data = communityList.get(position);

				if (data != null) {
					communityResp = data;
					whichCommunitySel = position;
					adapter.setWhichCommunitySel(whichCommunitySel);
					tv_community.setText(communityResp.getName());
				}
				dialog.dismiss();
			}
		});
	}
	
	/**
	 * 动态计算设置AbsListView高度
	 * 
	 * @函数名 setAbsListViewHeightBasedOnChildren
	 * @功能 TODO
	 * @param absListView
	 * @备注 <其它说明>
	 */
	private void setListViewHeightBasedOnChildren(ListView absListView) {

		ListAdapter listAdapter = absListView.getAdapter();
		if (listAdapter != null && listAdapter.getCount() > 0) {

			View view = listAdapter.getView(0, null, absListView);
			view.measure(0, 0);
			int totalHeight = 0;

			totalHeight = view.getMeasuredHeight() * 3;

			Log.i(TAG, "totalHeight = " + totalHeight);
			ViewGroup.LayoutParams params = absListView.getLayoutParams();
			params.height = totalHeight;
			absListView.setLayoutParams(params);
		}
	}

	/**
	 * 批复
	 * 
	 * @param approve
	 *            1表示通过 2表示拒绝
	 */
	private void approve(String approve) {

		// 没有授权任何人
		if (authorizationListResp == null) {
			return;
		}
		// 申请编号
		String id = authorizationListResp.getId();

		String bid = "";
		if (communityResp != null) {
			bid = communityResp.getBid();
		} else {
			ToastHelper.showMsg(DoorControlAuthorizationApproveActivity.this,
					"请选择小区", false);
			return;
		}
		long currentTime = DateUtils.getCurrentDate();
		long stop = 0;
		// 二次授权，0没有，1有
		String granttype = "";
		// 授权类型，0临时，1限时，2永久
		String autype = "";
		String starttime = currentTime + "";
		String stoptime = "";

		if ("1".equals(usertype)) {
			starttime = "0";
			stoptime = "0";
			granttype = "1";
			autype = "2";
		} else {
			autype = "1";
			granttype = "0";

			if ("2".equals(usertype)) {

				stop = currentTime + 3600 * 24 * 7;

			} else if ("3".equals(usertype)) {

				stop = currentTime + 3600 * 24;

			} else if ("4".equals(usertype)) {

				stop = currentTime + 3600 * 2;

			} else if ("5".equals(usertype)) {
				stop = currentTime + 3600 * 24 * 365;
			}

			starttime = DateUtils.phpToTimeString(currentTime + "");
			stoptime = DateUtils.phpToTimeString(stop + "");
		}

		// 备注
		String memo = "";

		if (doorControlService == null) {
			doorControlService = new DoorControlService(getApplicationContext());
		}
		// 处理中...
		showLoading(getString(R.string.processing));

		doorControlService.approveNew(id, bid, approve, usertype, autype,
				granttype, starttime, stoptime, memo,
				new GetOneRecordListener<String>() {

					@Override
					public void onFinish(String data) {
						hideLoading();

						setResult(RESULT_OK);
						finish();
					}

					@Override
					public void onFailed(String Message) {
						hideLoading();
						ToastHelper.showMsg(
								DoorControlAuthorizationApproveActivity.this,
								Message, false);
					}
				});
	}

	/**
	 * 再次授权
	 * 
	 * @param tel
	 */
	private void authorize() {

		// 没有授权任何人
		if (authorizationListResp == null) {
			return;
		}

		String toid = authorizationListResp.getToid();

		String bid = "";
		if (communityResp != null) {
			bid = communityResp.getBid();
		} else {
			ToastHelper.showMsg(DoorControlAuthorizationApproveActivity.this,
					"请选择小区", false);
			return;
		}
		long currentTime = DateUtils.getCurrentDate();
		long stop = 0;
		// 二次授权，0没有，1有
		String granttype = "";
		// 授权类型，0临时，1限时，2永久
		String autype = "";
		String starttime = currentTime + "";
		String stoptime = "";

		if ("1".equals(usertype)) {
			starttime = "0";
			stoptime = "0";
			granttype = "1";
			autype = "2";
		} else {
			autype = "1";
			granttype = "0";

			if ("2".equals(usertype)) {

				stop = currentTime + 3600 * 24 * 7;

			} else if ("3".equals(usertype)) {

				stop = currentTime + 3600 * 24;

			} else if ("4".equals(usertype)) {

				stop = currentTime + 3600 * 2;

			} else if ("5".equals(usertype)) {
				stop = currentTime + 3600 * 24 * 365;
			}
			starttime = DateUtils.phpToTimeString(currentTime + "");
			stoptime = DateUtils.phpToTimeString(stop + "");
		}

		// 备注
		String memo = "";

		if (doorControlService == null) {
			doorControlService = new DoorControlService(getApplicationContext());
		}
		// 处理中...
		showLoading(getString(R.string.processing));

		doorControlService.reAuthorize(toid, bid, usertype, granttype, autype,
				starttime, stoptime, memo, new GetOneRecordListener<String>() {

					@Override
					public void onFinish(String data) {
						hideLoading();

						setResult(RESULT_OK);
						finish();
					}

					@Override
					public void onFailed(String Message) {
						hideLoading();
						ToastHelper.showMsg(
								DoorControlAuthorizationApproveActivity.this,
								Message, false);
					}
				});
	}

	@Override
	public void backClicked() {

		if (!isShowingLoading()) {
			isBackAllowed = true;
		}
	}
}
